<template>
  <el-form ref="form" :model="user" :rules="rules" label-width="80px">
    <el-form-item :label="$t('role.nickName')" prop="nickName">
      <el-input v-model="user.nickName" />
    </el-form-item>
    <el-form-item :label="$t('role.phone')" prop="phonenumber">
      <el-input v-model="user.phone" maxlength="11" />
    </el-form-item>
    <el-form-item :label="$t('mechanism.mailbox')" prop="email">
      <el-input v-model="user.email" maxlength="50" />
    </el-form-item>
    <el-form-item :label="$t('calling.sex')">
      <el-radio-group v-model="user.sex">
        <el-radio label="0">{{ $t('calling.boy') }}</el-radio>
        <el-radio label="1">{{ $t('calling.girl') }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="mini" @click="submit">{{ $t('save') }}</el-button>
      <el-button type="danger" size="mini" @click="close">{{ $t('closeText') }}</el-button>
      <el-button type="danger" size="mini" @click="loginOut">{{ $t('cancellation') }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updateProfileMyself } from '@/api/system/user'

export default {
  props: {
    user: {
      type: Object,
      default: undefined
    }
  },
  data() {
    return {
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: this.$t('profile.userNameEmpty'), trigger: 'blur' }
        ],
        email: [
          { required: true, message: this.$t('profile.emailEmpty'), trigger: 'blur' },
          {
            type: 'email',
            message: this.$t('profile.emailRight'),
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          { required: false, message: this.$t('profile.phoneEmpty'), trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: this.$t('profile.phoneRight'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    submit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          console.log(JSON.stringify(this.user))
          updateProfileMyself(this.user).then(response => {
            if (response.code === 0) {
              this.msgSuccess(this.$t('loginLog.changeSuccess'))
              // this.$router.push({ path: '/wel/index' })
              location.reload()
            } else {
              this.msgError(response.msg)
            }
          })
        }
      })
    },

    loginOut() {
      this.$confirm(this.$t('exitSystem'), this.$t('tip'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('LogOut').then(() => {
          this.$router.push({ path: '/login' })
        })
      })
    },

    close() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.push({ path: '/wel/index' })
    }
  }
}
</script>
